package com.limao.DBProvider;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Types;
import java.util.ArrayList;

import com.limao.CacheManager.BaseDataCacheManager;
import com.limao.CacheManager.CrowdUserAuthCache;
import com.limao.DBDataClass.CrowdUserAuthClass;
import com.limao.DBDataClass.RMB_WithdrawDataClass;
import com.limao.DbConnection.DbConnectionManager;
import com.limao.Model.LzPluginException;
import com.limao.Model.PublicData;
import com.limao.Tool.CacheClass;
import com.limao.push.SysRmbRecTypeEnum;
import com.limao.push.pushToAPPTemplate;

public class RMB_WithdrawProvider {
	
	private static class DB_order_ProviderContainer {
		private static RMB_WithdrawProvider instance = new RMB_WithdrawProvider();
	}

	public static RMB_WithdrawProvider getInstance() {
		return DB_order_ProviderContainer.instance;
	}
	
	/** 0:待批 1已批　2提现成功 3拒绝,4导出数据,5:失败 **/
	public static final String[] TYPESTR = {"待批", "已批","提现成功","拒绝","导出数据","失败"};

	// 初始化 
	private RMB_WithdrawProvider() {

	}
	
	public String getTypeStr(int type) {
		if(type<90)
		{
			return type != -1 ? TYPESTR[type] : "未知来源";
		}
		else
		return TYPESTR[type];
	}
	
	
	
	// 新鲜宝   
	private RMB_WithdrawDataClass encapWithdrawOrderData(ResultSet rs) throws Exception{
		
		RMB_WithdrawDataClass orderData = new RMB_WithdrawDataClass();

		orderData.withdrawid = rs.getString("withdrawid") ; 						// 订单ID
		orderData.userid = rs.getString("userid");			// 购买用户ID
		orderData.cardtype = rs.getString("cardtype");
		orderData.cardno = rs.getString("cardno") ;
		orderData.cardname = rs.getString("cardname");
		orderData.cardbank = rs.getString("cardbank");

		orderData.rmb = rs.getString("rmb");
		
		orderData.istest = rs.getString("istest");
		
		orderData.state = rs.getString("state") ;
		orderData.statename=getTypeStr(CacheClass.getIntValue(orderData.state));
		
		orderData.time = rs.getString("time") ;
		orderData.timeAbout = CacheClass.getFormatDate(CacheClass.getLongValue(orderData.time),"yyyy年MM月dd日  HH:mm:ss");
		orderData.operid = rs.getString("operid");
		orderData.opername = rs.getString("opername");
		orderData.opertime = rs.getString("opertime");
		orderData.finishid = rs.getString("finishid");
		orderData.finishname = rs.getString("finishname");
		orderData.finishtime = rs.getString("finishtime");
		if(CacheClass.isEmpty(orderData.finishtime))
			orderData.finishtimeAbout="";
		else
			orderData.finishtimeAbout = CacheClass.getFormatDate(CacheClass.getLongValue(orderData.finishtime),"yyyy年MM月dd日  HH:mm:ss");
		orderData.errormsg = rs.getString("errormsg") ;
		if(CacheClass.isEmpty(orderData.errormsg))
			orderData.errormsg="无";
		return orderData;
		
	}
	
	//&新鲜宝     增加提现申请单
	public Boolean WithdrawAdd_Order(int userid, float rmb,float maxRmb)	throws LzPluginException 
	{

		boolean flag=false;
		CrowdUserAuthClass authTmp= CrowdUserAuthCache.getInstance().getUser(userid);
		if(CacheClass.isEmpty(authTmp.cardtype) || CacheClass.isEmpty(authTmp.cardno))
		{
			throw new LzPluginException("您的绑定提现帐号不正确");
		}
		
		// 数据库操作
		boolean abortTransaction = false;
		Connection con = null;
		ResultSet rs = null;
		PreparedStatement pstmt = null;
		// 生成ID号
		try {
			con = DbConnectionManager.getTransactionConnection();
			//用户扣掉积分
			
			pstmt = con.prepareCall("{call WithdrawRmb(?,?)}");
			pstmt.setInt(1, userid);
			BigDecimal h=CacheClass.toBigDecimal(rmb+"");
			pstmt.setBigDecimal(2,h);
			
            boolean hadResults=pstmt.execute();
            if (hadResults) {
               	rs=pstmt.getResultSet();
           		if(rs != null && rs.next())
           		{
           			flag=rs.getInt(1)>=1;
           		}
            }
            rs=null;
			if(!flag)
			{
				abortTransaction = true;
				throw new LzPluginException("可提现金额不足");
			}
			
			//取更新后的新值
			String nowrmb="0";
			DbConnectionManager.fastcloseStmt(rs,pstmt);
			pstmt = con.prepareStatement("select nowrmb from cd_user_rmb where userid=?");
			pstmt.setInt(1, userid);
			rs=pstmt.executeQuery();
			if(rs.next())
			{
				nowrmb=rs.getString("nowrmb");
			}
			long time=CacheClass.getTime();
			//增加　积分记录
			DbConnectionManager.fastcloseStmt(rs,pstmt);
			pstmt = con.prepareStatement("INSERT INTO cd_sys_rmb (userid,payuserid,rmb,level,type,time,name,image,nowrmb) VALUES (?,?,?,?,?,?,?,?,?)");
			pstmt.setInt(1, userid);
			pstmt.setInt(2, 0);
			pstmt.setFloat(3, 0-rmb);
			pstmt.setInt(4, 0);
			pstmt.setInt(5, SysRmbRecTypeEnum.type5.getIntVlue());
			pstmt.setLong(6, time);
			
			//0银行卡 1支付宝帐号 2微信支付帐号
			
			int type=CacheClass.getIntValue(authTmp.cardtype);
			switch(type)
			{
				case 0:
					pstmt.setString(7, "银行卡");
					break;
				case 1:
					pstmt.setString(7, "支付宝");
					break;	
				case 2:
					pstmt.setString(7, "微信支付");
					break;			
				default:
					pstmt.setString(7, "支付宝");
			}
			pstmt.setString(8, authTmp.avatar);
			pstmt.setBigDecimal(9, CacheClass.toBigDecimal(nowrmb));
			pstmt.execute();
			
			
			
			//生成订单
			DbConnectionManager.fastcloseStmt(rs,pstmt);
			pstmt = con.prepareStatement("INSERT INTO cd_sys_rmbwithdraw (userid,cardtype,cardno,cardname,cardbank,cardarea,rmb,state,time,istest) VALUES (?,?,?,?,?,?,?,?,?,?);");
			pstmt.setInt(1, userid);
			pstmt.setInt(2, CacheClass.getIntValue(authTmp.cardtype));
			pstmt.setString(3, authTmp.cardno);
			
			if(CacheClass.isEmpty(authTmp.cardname))
				pstmt.setNull(4, Types.VARCHAR);
			else
				pstmt.setString(4, authTmp.cardname);
			
			if(CacheClass.isEmpty(authTmp.cardbank))
				pstmt.setNull(5, Types.VARCHAR);
			else
				pstmt.setString(5, authTmp.cardbank);
			
			if(CacheClass.isEmpty(authTmp.cardarea))
				pstmt.setNull(6, Types.VARCHAR);
			else
				pstmt.setString(6, authTmp.cardarea);
			
						
			pstmt.setFloat(7, rmb);
			pstmt.setInt(8, 0);
			pstmt.setLong(9, time);
			pstmt.setInt(10, CacheClass.getIntValue(authTmp.istest));
			pstmt.execute();
			
			flag=true;

		} catch (Exception e) {
			flag=false;
			abortTransaction = true;
			e.printStackTrace();
		} finally {
			DbConnectionManager.closeTransactionConnection(rs,pstmt, con,abortTransaction);
		}
		
		if(!abortTransaction)//成功 更新相关缓存
		{
			CrowdUserAuthCache.getInstance().ClearObjectCache(userid+"");
			//消息推送
			pushToAPPTemplate.NewMess_WithDrawRmb(userid, rmb,0);
		}

		return flag;
	}
	
	//&新鲜宝  用户查询订单列表
	public PublicData load_WithdrawOrderList(int userid, int curpage,long sarttime,long endtime) {
		PublicData data = new PublicData();
		ArrayList<RMB_WithdrawDataClass> list = new ArrayList<RMB_WithdrawDataClass>();
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			String sql = "{call getRMBWithdrawList(?,?,?,?)}";
			con = DbConnectionManager.getConnection();
			pstmt = con.prepareCall(sql);
			pstmt.setInt(1, userid);
			pstmt.setInt(2, curpage);
			pstmt.setLong(3, sarttime);
			pstmt.setLong(4, endtime);
			pstmt.execute();

			rs = pstmt.getResultSet();
			while (rs.next()) {
				list.add(encapWithdrawOrderData(rs));
			}

			pstmt.getMoreResults();
			rs = pstmt.getResultSet();
			int total = 0;
			while (rs != null && rs.next()) {
				total = rs.getInt(1);
			}
			ArrayList<Object> returnlist = new ArrayList<Object>();

			if ((total % 20) > 0) {
				total = (total / 20 + 1);
			} else
				total = (total / 20);

			if (total == 0)
				total = 1;
			data.total = total + "";
			
			returnlist.addAll(list);
			data.curpage = curpage + "";
			data.list = returnlist;

		} catch (Exception e) {
			list = null;
			e.printStackTrace();
		} finally {
			DbConnectionManager.closeConnection(rs, pstmt, con);
		}

		return data;
	}
		
	
	//&新鲜宝    提现单详情记录
	public RMB_WithdrawDataClass load_WithdrawById(int withdrawid){
		RMB_WithdrawDataClass tmp = null;
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			
			con = DbConnectionManager.getConnection();
			pstmt = con.prepareStatement("select d.* ,auth.username as opername,auth0.username as finishname from cd_sys_rmbwithdraw as d" +
					" left join cd_user_auth as auth on auth.userid=d.operid " +
					" left join cd_user_auth as auth0 on auth0.userid=d.finishid where d.withdrawid=? ");
			pstmt.setInt(1, withdrawid);
			rs = pstmt.executeQuery();
			if (rs.next()) {
				tmp=encapWithdrawOrderData(rs);
			}
		} catch (Exception e) {
			tmp=null;
			e.printStackTrace();
		} finally {
			DbConnectionManager.closeConnection(rs, pstmt, con);
		}
		
		return tmp;
	}	
	
	//新鲜宝    提现是否过于频繁
	public boolean load_WithdrawByIdNum(int id){
		boolean tmp = false;
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		
		try {
			//系统参数
			int withdrawDay=CacheClass.getIntValue(BaseDataCacheManager.getInstance().Load_Param("withdrawDay"));
			int withdrawNum=CacheClass.getIntValue(BaseDataCacheManager.getInstance().Load_Param("withdrawNum"));
			
			con = DbConnectionManager.getConnection();
			pstmt = con.prepareStatement(" select COUNT(withdrawid) from cd_sys_rmbwithdraw where userid=? and (state!=3 and state!=5 ) and (TO_DAYS(from_unixtime(time/1000))>TO_DAYS(date_add( CURDATE() , interval -? day)))");
			pstmt.setInt(1, id);
			pstmt.setInt(2, withdrawDay);
			
			rs = pstmt.executeQuery();
			int num=0;
			if (rs.next()) {
				num=rs.getInt(1);
			}
			
			if(num<withdrawNum)
				tmp=true;
			else
				tmp=false;
			
		} catch (Exception e) {
			tmp=false;
			e.printStackTrace();
		} finally {
			DbConnectionManager.closeConnection(rs, pstmt, con);
		}
		
		return tmp;
	}		
	

}
